<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      label-width="auto"
      v-show="showSearch"
    >
      <el-row>
        <el-form-item label="生产单编码" prop="produceNo">
          <el-input
            v-model.trim="queryParams.produceNo"
            style="width: 180px"
            placeholder="请输入生产单编码"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="产品名称" prop="shipmentType">
          <el-input
            v-model.trim="queryParams.shipmentType"
            style="width: 180px"
            placeholder="请输入产品名称"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <!-- <el-form-item label="书刊编码" prop="bookCode">
                    <el-input
                        v-model.trim="queryParams.bookCode"
                        style="width: 180px"
                        placeholder="请输入书刊编码"
                        @keyup.enter="handleQuery"
                    />
                </el-form-item> -->
        <el-form-item label="出版编号" prop="pubNo">
          <el-input
            v-model.trim="queryParams.pubNo"
            style="width: 180px"
            placeholder="请输入出版编号"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <div class="operation">
          <el-button type="primary" icon="Search" @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          <el-button @click="advanced = !advanced">
            <a style="color: #448ef7">
              <el-icon v-if="advanced">
                <ArrowUpBold />
              </el-icon>
              <el-icon v-else>
                <ArrowDownBold />
              </el-icon>
            </a>
          </el-button>
        </div>
      </el-row>
      <el-row v-if="advanced">
        <!-- <el-form-item label="书刊名称" prop="bookName">
                    <el-input
                        v-model.trim="queryParams.bookName"
                        style="width: 180px"
                        placeholder="请输入书刊名称"
                        @keyup.enter="handleQuery"
                    />
                </el-form-item> -->
        <el-form-item label="下单日期" prop="submitDate">
          <el-date-picker
            style="width: 180px"
            v-model="queryParams.submitDate"
            value-format="YYYY-MM-DD "
            type="date"
            placeholder="请选择日期"
          />
        </el-form-item>
        <el-form-item label="定价" prop="fixPrice">
          <el-input
            v-model.trim="queryParams.fixPrice"
            style="width: 180px"
            placeholder="请输入定价"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="书号" prop="bookNo">
          <el-input
            v-model.trim="queryParams.bookNo"
            style="width: 180px"
            placeholder="请输入书号"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <!-- <el-form-item label="纸型" prop="paperType">
                    <el-input
                        v-model.trim="queryParams.paperType"
                        style="width: 180px"
                        placeholder="请输入纸型"
                        @keyup.enter="handleQuery"
                    />
                </el-form-item> -->
        <el-form-item label="定量" prop="weight">
          <el-input
            v-model.trim="queryParams.weight"
            style="width: 180px"
            placeholder="请输入定量"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <!-- <el-form-item label="内文承印长" prop="orderName">
                    <el-input v-model.trim="queryParams.orderName" style="width: 180px;" placeholder="请输入内文承印长"
                        @keyup.enter="handleQuery" />
                </el-form-item> -->
        <el-form-item label="送货单位" prop="customName">
          <el-input
            v-model.trim="queryParams.customName"
            style="width: 180px"
            placeholder="请输入送货单位"
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <!-- <el-form-item label="科目" prop="subjectType">
                    <el-select
                        style="width: 180px"
                        v-model="queryParams.subjectType"
                        placeholder="请选择科目"
                    >
                        <el-option
                            v-for="item in ems_workshop_subject_type"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item> -->
        <el-form-item label="订单数量" prop="orderCount">
          <el-input
            v-model.trim="queryParams.orderCount"
            type="number"
            style="width: 180px"
            placeholder="请输入订单数量"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="出版社" prop="publishingHouse">
          <el-input
            v-model.trim="queryParams.publishingHouse"
            style="width: 180px"
            placeholder="请输入出版社"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="车间" prop="workshopName">
          <el-select style="width: 180px" v-model="queryParams.workshopName">
            <el-option label="一车间" value="一车间"></el-option>
            <el-option label="四车间" value="四车间"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="印刷备注" prop="remark3">
          <el-input
            v-model.trim="queryParams.remark3"
            style="width: 180px"
            placeholder="请输入印刷备注"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="版材备注" prop="remark">
          <el-input
            v-model.trim="queryParams.remark"
            style="width: 180px"
            placeholder="请输入版材备注"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            style="width: 180px"
            filterable
            v-model="queryParams.status"
            placeholder="请选择状态"
          >
            <el-option
              v-for="item in ems_order_status"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否打包" prop="hasPackNum">
          <el-select style="width: 180px" v-model="queryParams.hasPackNum">
            <el-option label="是" value="1"></el-option>
            <el-option label="否" value=""></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="日期" style="width: 308px">
          <el-date-picker
            v-model="dateRange"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="版材尺寸" prop="sheetSize">
          <el-select
            clearable
            style="width: 100%"
            v-model="queryParams.sheetSize"
            placeholder="请选择版材尺寸"
          >
            <el-option
              v-for="item in ems_machine_info_size"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          >新增</el-button
        >
        <el-button
          type="primary"
          plain
          icon="Delete"
          :disabled="multiple"
          v-hasPermi="['text:bookNo:delete']"
          @click="handleDeleteBookNo"
        >
          书号删除
        </el-button>
        <el-button
          type="primary"
          :disabled="multiple"
          plain
          icon="Printer"
          @click="handlePrintList"
          >打印</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <!-- <el-button type="primary" plain icon="Download" @click="handleExport">导出</el-button> -->
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
        :columns="columns"
      ></right-toolbar>
    </el-row>
    <div>
      <!-- @row-click="onRowClick" -->
      <el-table
        v-loading="loading"
        row-key="produceId"
        :summary-method="getSummaries"
        height="65vh"
        show-summary
        highlight-current-row
        @selection-change="handleSelectionChange"
        border
        :data="dataList"
      >
        <!-- :selectable="selectable" -->
        <el-table-column type="selection" align="center" width="40" />
        <el-table-column
          label="序号"
          fixed="left"
          width="60"
          type="index"
          align="center"
        />
        <el-table-column
          label="状态"
          fixed="left"
          min-width="100"
          align="center"
          :show-overflow-tooltip="true"
          prop="status"
          v-if="columns[0].visible"
        >
          <template v-slot="{ row }">
            <dict-tag :options="ems_order_status" :value="row.status" />
          </template>
        </el-table-column>
        <el-table-column
          label="数据状态"
          min-width="80"
          align="center"
          :show-overflow-tooltip="true"
          prop="isSuspend"
          v-if="columns[0].visible"
        >
          <template v-slot="{ row }">
            <el-tag
              :type="row.isSuspend == 1 ? 'error' : 'success'"
              effect="dark"
              round
            >
              {{ row.isSuspend == 1 ? "暂停" : "正常" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="车间"
          width="80"
          align="center"
          prop="workshopName"
          v-if="columns[0].visible"
        >
          <!-- <template v-slot="{ row }">
                        <dict-tag :options="ems_workshop" :value="row.workshopName" />
                    </template> -->
        </el-table-column>
        <el-table-column
          label="新/旧版"
          align="center"
          width="80"
          prop="isNew"
          v-if="columns[2].visible"
        >
          <template v-slot="{ row }">
            <dict-tag :options="ems_produce_is_new" :value="row.isNew" />
          </template>
        </el-table-column>
        <el-table-column
          label="版材备注"
          width="300"
          align="center"
          :show-overflow-tooltip="true"
          prop="remark"
        >
          <template v-slot="{ row }"> {{ row.remark }}</template>
        </el-table-column>
        <el-table-column
          label="生产单编码"
          width="220"
          align="center"
          prop="orderNo"
          v-if="columns[1].visible"
        >
          <template v-slot="{ row }">
            <el-button type="primary" @click.stop="handleView(row)" text>
              <span style="font-size: 16px">
                {{ row.produceNo.slice(0, -4) }}
              </span>
              <span style="font-size: 24px">
                {{ row.produceNo.slice(-4) }}
              </span>
            </el-button>
          </template>
        </el-table-column>

        <el-table-column
          label="出版编号"
          min-width="120"
          align="center"
          prop="pubNo"
          v-if="columns[3].visible"
        ></el-table-column>
        <el-table-column
          label="产品名称"
          min-width="240"
          align="center"
          prop="shipmentType"
          v-if="columns[3].visible"
        >
          <template v-slot="{ row }">
            <span
              style="color: #409eff; cursor: pointer"
              @click.stop="onRowClick(row)"
            >
              {{ row.shipmentType }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          label="订单数量"
          width="100"
          align="center"
          prop="orderCount"
          v-if="columns[3].visible"
        ></el-table-column>
        <el-table-column
          label="书号"
          min-width="160"
          align="center"
          prop="bookNo"
        />
        <el-table-column
          label="版材集合"
          width="120"
          align="center"
          prop="sheetSize"
        >
          <template v-slot="{ row }">
            <!-- sheetSizeList -->
            <dict-tag
              v-for="(item, index) in row.sheetSizeList?.split('+')"
              :key="index"
              :options="ems_machine_info_size"
              :value="item"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="下单日期"
          min-width="120"
          align="center"
          prop="submitDate"
          v-if="columns[4].visible"
        >
          <template v-slot="{ row }">
            {{ row.submitDate?.split("T")[0] ?? "" }}
          </template>
        </el-table-column>
        <el-table-column
          label="交货日期"
          min-width="120"
          align="center"
          prop="deliverDate"
          v-if="columns[5].visible"
        >
          <template v-slot="{ row }">
            {{ row.deliverDate?.split("T")[0] ?? "" }}
          </template>
        </el-table-column>
        <el-table-column
          label="加急交货日期"
          style="color: red"
          min-width="120"
          align="center"
          prop="urgentDate"
          v-if="columns[5].visible"
        >
          <template v-slot="{ row }">
            <span style="color: red">
              {{ parseTime(row.urgentDate) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          label="加急交货数量"
          width="90"
          align="center"
          prop="urgentNum"
        >
          <template v-slot="{ row }">
            <span style="color: red">
              {{ row.urgentNum == 0 ? "" : row.urgentNum }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          label="定价"
          width="80"
          align="center"
          prop="fixPrice"
        />

        <el-table-column
          label="出版社"
          width="120"
          align="center"
          prop="publishingHouse"
        />

        <el-table-column
          label="包内数量"
          width="80"
          align="center"
          prop="packInNum"
        />
        <el-table-column
          label="送货单位"
          width="120"
          align="center"
          prop="customName"
        />
        <el-table-column
          label="印张集合"
          width="120"
          align="center"
          prop="sheetList"
        />

        <el-table-column
          label="印色集合"
          width="120"
          align="center"
          prop="printColor"
        >
          <template v-slot="{ row }">
            <dict-tag
              v-for="(item, index) in row.printColor?.split(',')"
              :key="index"
              :options="ems_order_print_color"
              :value="item"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="制单日期"
          width="120"
          align="center"
          prop="createTime"
        >
          <template v-slot="{ row }">
            {{ row.createTime.split("T")[0] }}
          </template>
        </el-table-column>
        <el-table-column
          label="印刷备注"
          min-width="120"
          align="center"
          :show-overflow-tooltip="true"
          prop="remark3"
        ></el-table-column>
        <el-table-column
          label="操作"
          align="center"
          min-width="160"
          fixed="right"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-tooltip
              content="修改"
              placement="top"
              v-if="scope.row.status == 1"
            >
              <el-button
                link
                type="primary"
                icon="Edit"
                @click.stop="handleUpdate(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              content="删除"
              placement="top"
              v-if="scope.row.status == 1"
            >
              <el-button
                link
                type="primary"
                icon="Delete"
                @click.stop="handleDelete(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="复制新增" placement="top">
              <el-button
                link
                type="primary"
                v-if="scope.row.isSuspend != 1"
                icon="CopyDocument"
                @click.stop="handleCopy(scope.row)"
              ></el-button>
            </el-tooltip>
            <!-- <el-tooltip content="打印" placement="top">
                            <el-button
                                link
                                type="primary"
                                icon="Printer"
                                @click="handlePrint(scope.row)"
                            ></el-button>
                        </el-tooltip> -->
            <el-button
              link
              type="primary"
              v-if="scope.row.status == 1"
              @click.stop="handleSubmit(scope.row)"
            >
              提交
            </el-button>
            <el-button
              link
              type="primary"
              @click.stop="handleInvalidate(scope.row)"
            >
              作废
            </el-button>
            <el-button
              link
              type="primary"
              v-if="scope.row.isSuspend != 1"
              @click.stop="handleUrgentDate(scope.row)"
            >
              加急
            </el-button>
            <el-button
              link
              type="primary"
              v-if="scope.row.status == 2 && scope.row.makeStatus == 1"
              @click.stop="handleBack(scope.row)"
            >
              撤回
            </el-button>
            <el-button
              link
              type="primary"
              v-hasPermi="['text:back:auto']"
              @click.stop="handleAutoBack(scope.row)"
            >
              一键撤回
            </el-button>
            <el-button
              link
              type="primary"
              v-if="scope.row.isSuspend != 1"
              @click.stop="handleChangePiece(scope.row)"
            >
              换片
            </el-button>
            <el-button
              link
              type="primary"
              v-hasPermi="['text:suspend']"
              v-if="scope.row.status > 2 && scope.row.isSuspend != 1"
              @click.stop="handleSuspend(scope.row)"
            >
              暂停
            </el-button>
            <el-button
              link
              type="primary"
              v-hasPermi="['text:suspend']"
              v-if="scope.row.isSuspend == 1"
              @click.stop="handleRestore(scope.row)"
            >
              取消暂停
            </el-button>
            <el-button
              link
              type="primary"
              v-hasPermi="['text:update:paper']"
              v-if="
                (scope.row.isSuspend != 1 && scope.row.status < 6) ||
                scope.row.status == 19
              "
              @click.stop="handleOtherPaper(scope.row)"
            >
              换纸
            </el-button>
            <el-button
              link
              type="primary"
              v-hasPermi="['text:contact:cover']"
              @click.stop="handleContactCover(scope.row)"
            >
              关联封面
            </el-button>
            <el-button
              link
              type="primary"
              v-hasPermi="['text:pack:num']"
              @click.stop="handleUpdatePackInNum(scope.row)"
            >
              改包
            </el-button>
            <el-button
              link
              type="primary"
              v-hasPermi="['text:update:yunwei']"
              @click.stop="handleOtherPaper(scope.row)"
            >
              改
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    <!-- 用户导入对话框 -->
    <el-dialog
      :title="upload.title"
      v-model="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox v-model="upload.updateSupport" />
              是否更新已经存在的用户数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link
              type="primary"
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              @click="importTemplate"
            >
              下载模板
            </el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      title="生产单加急"
      v-model="urgentOpen"
      width="35%"
      append-to-body
      @close="closed"
    >
      <el-form
        :model="queryDate"
        ref="queryDateForm"
        :rules="rules"
        :inline="true"
      >
        <el-form-item label="加急交货日期" prop="urgentDate">
          <el-date-picker
            style="width: 200px"
            v-model="queryDate.urgentDate"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            date-format="MMM DD, YYYY"
            time-format="HH:mm"
            type="datetime"
            placeholder="请选择时间"
          />
        </el-form-item>
        <el-form-item label="加急交货数量" prop="urgentNum">
          <el-input
            v-model.trim="queryDate.urgentNum"
            type="number"
            style="width: 200px"
            placeholder="请输入加急交货数量"
          />
        </el-form-item>
      </el-form>
      <div class="footer">
        <el-button type="primary" @click="submitFill">确定</el-button>
        <el-button @click="urgentOpen = false">取消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="生产单换片"
      v-model="changePieceOpen"
      width="35%"
      append-to-body
      @close="closedChangePiece"
    >
      <el-form
        :model="queryChange"
        ref="queryChangePieceForm"
        :rules="rules"
        :inline="true"
      >
        <el-form-item label="换片内容" prop="changePiece">
          <el-input
            v-model="queryChange.changePiece"
            type="textarea"
            style="width: 450px"
            placeholder="请输入换片内容"
          ></el-input>
        </el-form-item>
      </el-form>
      <div class="footer">
        <el-button type="primary" @click="submitChangePiece">确定</el-button>
        <el-button @click="changePieceOpen = false">取消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="生产单换纸"
      v-model="paperOpen"
      width="80%"
      append-to-body
      @close="
        () => {
          paperOpen = false;
        }
      "
    >
      <el-table
        :data="producePrintList"
        row-key="printId"
        ref="producePrintListRef"
        v-loading="printLoading"
        border
      >
        <el-table-column label="序号" width="60" type="index" align="center" />
        <el-table-column
          label="品种"
          prop="breed"
          min-width="160"
          align="center"
        >
        </el-table-column>
        <el-table-column
          label="组成"
          min-width="160"
          prop="composition"
          align="center"
        >
          <template #default="scope">
            <dict-tag
              :options="ems_order_make_up"
              :value="scope.row.composition"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="印张"
          width="100"
          prop="sheet"
          align="center"
        ></el-table-column>
        <el-table-column
          label="贴标"
          width="120"
          prop="labeling"
          align="center"
        >
        </el-table-column>
        <el-table-column
          label="印数"
          width="120"
          prop="printAmount"
          align="center"
        ></el-table-column>
        <el-table-column
          label="用纸令数"
          width="120"
          prop="reamAmount"
          align="center"
        ></el-table-column>
        <el-table-column
          label="损耗系数"
          width="100"
          prop="lossCoefficient"
          align="center"
        >
        </el-table-column>
        <el-table-column
          label="损耗令数"
          width="120"
          prop="lossReam"
          align="center"
        ></el-table-column>
        <el-table-column
          label="用纸总令数"
          width="120"
          prop="totalReamAmount"
          align="center"
        ></el-table-column>
        <el-table-column
          label="吨位系数"
          width="120"
          prop="tonnageCoefficient"
          align="center"
        >
        </el-table-column>
        <el-table-column
          label="印刷方式"
          prop="printType"
          width="120"
          align="center"
        >
          <template #default="scope">
            <dict-tag
              :options="mes_paper_package"
              :value="scope.row.printType"
            />
          </template>
        </el-table-column>

        <el-table-column
          label="轮转吨数"
          width="120"
          prop="rotateTon"
          align="center"
        >
        </el-table-column>
        <el-table-column
          label="版材尺寸"
          prop="sheetSize"
          min-width="125"
          align="center"
        >
          <template #default="scope">
            <dict-tag
              :options="ems_machine_info_size"
              :value="scope.row.sheetSize"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="另行加放"
          width="120"
          prop="lxjf"
          align="center"
        >
        </el-table-column>
        <el-table-column
          label="成品尺寸"
          width="120"
          prop="finishSize"
          align="center"
        >
          <template #default="scope">
            <dict-tag
              :options="ems_produce_finish_size"
              :value="scope.row.finishSize"
            />
          </template>
        </el-table-column>

        <!-- <el-table-column
          label="工艺"
          min-width="160"
          prop="technologyId"
          align="center"
        >
          <template #default="scope">
            <el-select
              disabled
              clearable
              style="width: 100%"
              v-model="scope.row.technologyId"
              placeholder="请选择工艺"
            >
              <el-option
                v-for="item in technologyList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </template>
        </el-table-column> -->
        <el-table-column
          label="印刷"
          min-width="120"
          prop="printMachine"
          :show-overflow-tooltip="true"
          align="center"
        >
        </el-table-column>

        <el-table-column
          label="半代裁切"
          min-width="120"
          prop="whitecuttingMachine"
          :show-overflow-tooltip="true"
          align="center"
        >
        </el-table-column>
        <el-table-column
          label="封面裁切"
          min-width="120"
          prop="covercuttingMachine"
          :show-overflow-tooltip="true"
          align="center"
        >
        </el-table-column>

        <el-table-column
          label="覆膜"
          min-width="120"
          prop="coveringMachine"
          :show-overflow-tooltip="true"
          align="center"
        >
        </el-table-column>

        <el-table-column
          label="折页"
          min-width="120"
          prop="foldMachine"
          :show-overflow-tooltip="true"
          align="center"
        >
        </el-table-column>

        <el-table-column
          label="装订"
          min-width="120"
          :show-overflow-tooltip="true"
          prop="bindingMachine"
          align="center"
        >
        </el-table-column>
        <el-table-column
          label="纸张规格"
          width="120"
          fixed="right"
          prop="paperSpecifications"
          align="center"
        >
          <template #default="scope">
            <dict-tag
              :options="mes_paper_specs"
              :value="scope.row.paperSpecifications"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="下单印数"
          width="120"
          prop="orderPrintCount"
          align="center"
        >
        </el-table-column>

        <el-table-column
          label="纸型"
          width="120"
          prop="paperType"
          align="center"
        >
          <template #default="scope">
            <dict-tag :options="mes_paper_type" :value="scope.row.paperType" />
          </template>
        </el-table-column>
        <el-table-column
          label="定量"
          min-width="120"
          fixed="right"
          prop="weight"
          align="center"
        ></el-table-column>
        <el-table-column
          label="幅宽"
          width="120"
          fixed="right"
          prop="clothWidth"
          align="center"
        ></el-table-column>
        <el-table-column
          label="品牌"
          fixed="right"
          width="120"
          prop="brand"
          align="center"
        >
          <template #default="scope">
            <dict-tag :options="mes_paper_brand" :value="scope.row.brand" />
          </template>
        </el-table-column>
        <el-table-column
          label="印刷序列号"
          min-width="120"
          prop="printProduceNo"
          align="center"
        ></el-table-column>
        <el-table-column label="备注" width="120" prop="remark" align="center">
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="80"
          fixed="right"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-button
              link
              type="primary"
              @click.stop="handleUpdatePaper(scope.row, scope.$index)"
              >修改</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="footer" style="margin-top: 15px">
        <el-button
          type="primary"
          :loading="paperBtnLoading"
          @click="submitChangePaper"
          >换 纸</el-button
        >
        <el-button @click="paperOpen = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="生产单作废"
      v-model="cancelChooseOpen"
      width="35%"
      append-to-body
      @close="closedCancelChoose"
    >
      <el-form
        :model="queryCancel"
        ref="querycancelForm"
        :rules="rules"
        :inline="true"
      >
        <el-form-item label="作废选项" prop="cancelChoose">
          <input
            type="radio"
            id="option1"
            value="单据作废"
            v-model="queryCancel.cancelChoose"
          />
          <label for="option1">单据作废</label>
          <input
            type="radio"
            id="option2"
            value="文件作废"
            v-model="queryCancel.cancelChoose"
          />
          <label for="option2">文件作废</label>
        </el-form-item>
      </el-form>
      <div class="footer">
        <el-button type="primary" @click="submitCancelChoose">确定</el-button>
        <el-button @click="cancelChooseOpen = false">取消</el-button>
      </div>
    </el-dialog>
    <printNW
      :visible="printOpen"
      :printList="printList"
      @cancel="
        () => {
          printOpen = false;
          mainId = '';
          printList = [];
        }
      "
      :id="mainId"
    ></printNW>

    <orderInfo
      :visible="orderInfoOpen"
      @cancel="
        () => {
          orderInfoOpen = false;
          orderInfoId = '';
        }
      "
      :id="orderInfoId"
    ></orderInfo>
    <SearchPaperCoding
      :visible="paperCodingOpen"
      :packageType="selectPackageType"
      :useType="'1'"
      @changeUpdate="changePaperData"
      @cancel="
        () => {
          paperCodingOpen = false;
        }
      "
    ></SearchPaperCoding>
    <updateAssociationCover
      :visible="isShowProduct"
      @cancel="
        () => {
          isShowProduct = false;
          updateTextId = '';
        }
      "
      :id="updateTextId"
    >
    </updateAssociationCover>
  </div>
</template>

<script setup name="order">
import printNW from "./printNW.vue";
import { downLoad } from "@/utils/ruoyi";
import useTagsViewStore from "@/store/modules/tagsView";
import SearchPaperCoding from "@/components/SearchPaperCoding";
import updateAssociationCover from "./updateAssociationCover.vue";
import orderInfo from "./orderInfo.vue";
const tagsViewStore = useTagsViewStore();
import {
  getProduceOrderList,
  delProduceById,
  updateUrgentDate,
  updateStatus,
  updateChangePiece,
  updatebookNo,
  updatesuspend,
  getProduceById,
  upProducePrint,
  upPackInNum,
  withdraw,
} from "@/api/production/cover";
import { ElMessageBox } from "element-plus";

const { proxy } = getCurrentInstance();
const printOpen = ref(false);
const mainId = ref("");
const loading = ref(true);
const dataList = ref([]);
const orderInfoId = ref("");
const paperOpen = ref(false);
const showSearch = ref(true);
const total = ref(0);
const advanced = ref(false);
const urgentOpen = ref(false);
const changePieceOpen = ref(false);
const cancelChooseOpen = ref(false);
const selectPackageType = ref("");
const selectId = ref(undefined);
const selectNo = ref(undefined);
const queryDateForm = ref(null);
const countTotal = ref(0);
const producePrintList = ref([]);
const querycancelForm = ref(null);
const queryChangePieceForm = ref(null);
const orderInfoOpen = ref(false);
const multiple = ref(true);
const selectBookNo = ref([]);
const dateRange = ref();
const router = useRouter();
const selectRow = ref([]);
const selectChangeRow = ref("");
const printList = ref([]);
const printLoading = ref(false);
const paperCodingOpen = ref(false);
const selectPrintId = ref("");
const paperBtnLoading = ref(false);
const isShowProduct = ref(false);
const updateTextId = ref("");
import { getToken } from "@/utils/auth";
import { ref } from "@vue/reactivity";
/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/mes/user/importMesUserInfo",
});
// 列显隐信息
const columns = ref([
  { key: 0, label: `状态`, visible: true },
  { key: 1, label: `生产单编码`, visible: true },
  { key: 2, label: `新/旧版`, visible: true },
  { key: 3, label: `出版编号`, visible: true },
  { key: 4, label: `下单日期`, visible: true },
  { key: 5, label: `加急交货日期`, visible: true },
  { key: 6, label: `备注`, visible: true },
  { key: 7, label: `车间`, visible: true },
]);

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 50,
    type: 2,
    orderName: undefined,
    orderNo: undefined,
  },
  queryDate: {
    urgentDate: undefined,
  },
  rules: {
    // urgentDate: [
    //   { required: true, message: "加急交货日期不能为空", trigger: "blur" },
    // ],
  },
  queryChange: {
    changePiece: null,
  },
  queryCancel: {
    changeChoose: null,
  },
});
const { queryParams, queryDate, rules, queryChange, queryCancel } =
  toRefs(data);
const {
  mes_paper_brand,
  ems_order_make_up,
  mes_paper_package,
  ems_produce_finish_size,
  ems_order_print_color,
  ems_machine_info_size,
  ems_workshop_subject_type,
  ems_order_status,
  ems_produce_is_new,
  ems_workshop,
  mes_paper_type,
  mes_paper_specs,
} = proxy.useDict(
  "mes_paper_brand",
  "ems_order_make_up",
  "mes_paper_package",
  "ems_produce_finish_size",
  "mes_paper_type",
  "mes_paper_specs",
  "ems_order_print_color",
  "ems_machine_info_size",
  "ems_order_status",
  "ems_workshop_subject_type",
  "ems_produce_is_new",
  "ems_workshop"
);

// 多选打印
const handlePrintList = () => {
  printOpen.value = true;
  printList.value = selectRow.value;
};
const selectable = (row, index) => {
  if (row.bookNo) {
    return true;
  }
};

const handleSelectionChange = (row) => {
  selectRow.value = row;
  selectBookNo.value = row.map((item) => item.produceId);
  multiple.value = !row.length;
};
const onRowClick = (row) => {
  orderInfoOpen.value = true;
  orderInfoId.value = row.produceId;
};

//  关联生产单
const handleContactCover = (row) => {
  isShowProduct.value = true;
  updateTextId.value = row.produceId;
};
// 改包
const handleUpdatePackInNum = (row) => {
  ElMessageBox.prompt("请输入包内数量", "温馨提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    inputPattern: /^[1-9]\d*(\.\d+)?$/,
    inputErrorMessage: "请输入",
  }).then(({ value }) => {
    upPackInNum({ produceId: row.produceId, packInNum: value }).then((res) => {
      proxy.$modal.msgSuccess("修改成功");
      getList();
    });
  });
};

// 换纸
const handleOtherPaper = (row) => {
  paperOpen.value = true;
  printLoading.value = true;
  getProduceById({ pid: row.produceId })
    .then((res) => {
      printLoading.value = false;
      producePrintList.value = res.data.producePrintList;
    })
    .catch((err) => {});
};
// 换纸
const handleUpdatePaper = (row, index) => {
  selectPrintId.value = row.printId;
  selectPackageType.value = row.printType;
  paperCodingOpen.value = true;
};
// 选中的纸
const changePaperData = (row) => {
  const itemToUpdate = producePrintList.value.find(
    (item) => item.printId === selectPrintId.value
  );
  if (itemToUpdate) {
    itemToUpdate.paperSpecifications = row.specs;
    itemToUpdate.paperNo = row.code;
    itemToUpdate.paperName = row.name;
    itemToUpdate.weight = row.weight;
    itemToUpdate.clothWidth = row.longWide;
    itemToUpdate.brand = row.brand;
    itemToUpdate.paperType = row.paperType;
  }
  paperCodingOpen.value = false;
};

// 接口改纸
const submitChangePaper = () => {
  proxy.$modal
    .confirm('是否确认换纸"')
    .then(function () {
      paperBtnLoading.value = true;
      return upProducePrint(producePrintList.value);
    })
    .then(() => {
      // getList();
      paperOpen.value = false;
      paperBtnLoading.value = false;
      proxy.$modal.msgSuccess("换纸成功");
    })
    .catch(() => {
      // paperBtnLoading.value = false;
    });
};
// 删除书号
const handleDeleteBookNo = () => {
  proxy.$modal
    .confirm("是否确认删除书号？")
    .then(function () {
      return updatebookNo(selectBookNo.value);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
};
// 合计
const getSummaries = (param) => {
  const { columns, data } = param;
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 1) {
      sums[index] = "合计";
      return;
    }
    switch (column.property) {
      case "orderCount":
        sums[index] = countTotal.value;
        break;
      default:
        break;
    }
  });
  return sums;
};
const tableRowClassName = ({ row, rowIndex }) => {
  return "success-row";
};
const getList = () => {
  loading.value = true;
  getProduceOrderList({
    ...queryParams.value,
    startTime: Array.isArray(dateRange.value) ? dateRange.value[0] : undefined,
    endTime:
      Array.isArray(dateRange.value) > 0 ? dateRange.value[1] : undefined,
  })
    .then((res) => {
      loading.value = false;
      dataList.value = res.rows;
      countTotal.value = res.rows[0]?.countTotal;
      // if (res.rows.length > 0) {
      //     mainId.value = res.rows[0].produceId
      // }
      total.value = res.total;
    })
    .catch((err) => {
      loading.value = false;
    });
};
// 暂停
const handleSuspend = (row) => {
  proxy.$modal
    .confirm('是否确认暂停"' + row.produceNo + '"的生产单？')
    .then(function () {
      return updatesuspend({ isSuspend: 1, pid: row.produceId });
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("暂停成功");
    })
    .catch(() => {});
};
// 取消暂停
const handleRestore = (row) => {
  proxy.$modal
    .confirm('是否确认取消暂停"' + row.produceNo + '"的生产单？')
    .then(function () {
      return updatesuspend({ isSuspend: 2, pid: row.produceId });
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("取消暂停成功");
    })
    .catch(() => {});
};
// 打印
const handlePrint = (row) => {
  printOpen.value = true;
  mainId.value = row.produceId;
};
// 新增
const handleAdd = () => {
  tagsViewStore.delView({
    name: "textDetails",
    path: "/production/text/textDetails",
  });
  router.push("/production/text/textDetails");
};
// 编辑
const handleUpdate = (row) => {
  router.push({
    path: "/production/text/textDetails",
    query: {
      id: row.produceId,
    },
  });
};
// 查看
const handleView = (row) => {
  router.push({
    path: "/production/text/textDetails",
    query: {
      id: row.produceId,
      info: true,
    },
  });
};
// 复制新增
const handleCopy = (row) => {
  router.push({
    path: "/production/text/textDetails",
    query: {
      id: row.produceId,
      copy: true,
    },
  });
};

// 提交
const handleSubmit = (row) => {
  proxy.$modal
    .confirm('是否确认提交"' + row.produceNo + '"的生产单？')
    .then(function () {
      return updateStatus({ status: 2, pid: row.produceId });
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("提交成功");
    })
    .catch(() => {});
};

// 撤回
const handleBack = (row) => {
  proxy.$modal
    .confirm('是否确认撤回"' + row.produceNo + '"的生产单？')
    .then(function () {
      return updateStatus({ status: 1, pid: row.produceId });
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("撤回成功");
    })
    .catch(() => {});
};
// 撤回
const handleAutoBack = (row) => {
  proxy.$modal
    .confirm('是否确认一键撤回"' + row.produceNo + '"的生产单？')
    .then(function () {
      loading.value = true;
      return withdraw({ produceId: row.produceId });
    })
    .then(() => {
      loading.value = false;
      getList();
      proxy.$modal.msgSuccess("撤回成功");
    })
    .catch(() => {
      loading.value = false;
    });
};
// 作废
const handleInvalidate = (row) => {
  selectId.value = row.produceId;
  selectNo.value = row.produceNo;
  cancelChooseOpen.value = true;

  // proxy.$modal
  //     .confirm('是否确认作废"' + row.produceNo + '"的生产单？')
  //     .then(function () {
  //         return updateStatus({ status: 0, pid: row.produceId })
  //     })
  //     .then(() => {
  //         getList()
  //         proxy.$modal.msgSuccess('作废成功')
  //     })
  //     .catch(() => {})
};
// 获取当前时间
const getCurrentDateTime = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, "0");
  const day = String(now.getDate()).padStart(2, "0");
  const hours = String(now.getHours()).padStart(2, "0");
  const minutes = String(now.getMinutes()).padStart(2, "0");
  const seconds = String(now.getSeconds()).padStart(2, "0");
  let submitDate = `${year}-${month}-${day}`;
  // 将字符串转换为日期对象
  const submitDateObj = new Date(`${year}-${month}-${day}`);
  // 增加4天
  submitDateObj.setDate(submitDateObj.getDate() + 3);
  // 重新格式化为字符串
  submitDate = `${submitDateObj.getFullYear()}-${String(
    submitDateObj.getMonth() + 1
  ).padStart(2, "0")}-${String(submitDateObj.getDate()).padStart(
    2,
    "0"
  )} ${hours}:${minutes}:${seconds}`;
  return submitDate;
};
// 加急
const handleUrgentDate = (row) => {
  //默认交货日期
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, "0");
  const day = String(now.getDate()).padStart(2, "0");
  // 将字符串转换为日期对象
  const submitDateObj = new Date(`${year}-${month}-${day}`);
  // 增加3天
  submitDateObj.setDate(submitDateObj.getDate() + 3);
  // 重新格式化为字符串
  queryDate.value.urgentDate = `${submitDateObj.getFullYear()}-${String(
    submitDateObj.getMonth() + 1
  ).padStart(2, "0")}-${String(submitDateObj.getDate()).padStart(
    2,
    "0"
  )} 00:00:00`;
  // queryDate.value.urgentDate = row.deliverDate?.split('T')[0] + ' 00:00:00' ?? ''
  selectId.value = row.produceId;
  urgentOpen.value = true;
  queryDate.value.urgentDate = getCurrentDateTime();
};

//换片
const handleChangePiece = (row) => {
  selectChangeRow.value = row;
  // queryChange.value.changePiece = row.changePiece;
  selectId.value = row.produceId;
  changePieceOpen.value = true;
};

const closed = () => {
  proxy.resetForm("queryDateForm");
};
const submitFill = (row) => {
  queryDateForm.value.validate((valid) => {
    if (valid) {
      updateUrgentDate({ ...queryDate.value, pid: selectId.value }).then(
        (res) => {
          urgentOpen.value = false;
          proxy.$modal.msgSuccess("加急成功");
          getList();
        }
      );
    }
  });
};

//提交换片内容
const submitChangePiece = () => {
  queryChangePieceForm.value.validate((valid) => {
    if (valid) {
      const remark =
        queryChange.value.changePiece + " " + selectChangeRow.value.remark;
      updateChangePiece({ remark, pid: selectId.value }).then((res) => {
        changePieceOpen.value = false;
        proxy.$modal.msgSuccess("换片成功");
        getList();
      });
    }
  });
};
//关闭换片内容
const closedChangePiece = () => {
  proxy.resetForm("queryChangePieceForm");
};
//关闭作废选项
const closedCancelChoose = () => {
  proxy.resetForm("querycancelForm");
};

//提交作废选项
//选择单据作废，就执行现在的作废方式，直接生产单作废，如果是文件作废，状态改成文件作废，相对应的bom清单也作废
const submitCancelChoose = () => {
  if (queryCancel.value.cancelChoose == "单据作废") {
    proxy.$modal
      .confirm('是否确认作废"' + selectNo.value + '"的生产单？')
      .then(function () {
        return updateStatus({ status: 0, pid: selectId.value });
      })
      .then(() => {
        cancelChooseOpen.value = false;
        getList();
        proxy.$modal.msgSuccess("单据作废成功");
      })
      .catch(() => {});
  } else if (queryCancel.value.cancelChoose == "文件作废") {
    proxy.$modal
      .confirm('是否确认作废"' + selectNo.value + '"的生产单和对应的bom清单？')
      .then(function () {
        return updateStatus({ status: -2, pid: selectId.value });
      })
      .then(() => {
        cancelChooseOpen.value = false;
        getList();
        proxy.$modal.msgSuccess("文件作废成功");
      })
      .catch(() => {});
  }
};

// 搜索
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};
/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
};
/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal
    .confirm('是否确认删除"' + row.produceNo + '"生产单？')
    .then(function () {
      return delProduceById({ pid: row.produceId });
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}
// 导出
const handleExport = () => {
  exportMesOrder(queryParams.value).then((res) => {
    downLoad(res.msg, "订单列表");
  });
};
/** 导入按钮操作 */
function handleImport() {
  upload.title = "员工导入";
  upload.open = true;
}
/** 下载模板操作 */
function importTemplate() {
  exportTemplate().then((res) => {
    downLoad(res.msg, "人员模版");
  });
}
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert(
    "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
      response.msg +
      "</div>",
    "导入结果",
    { dangerouslyUseHTMLString: true }
  );
  getList();
};

/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
}
getList();
// router.beforeEach((to, from, next) => {
//     if (to.path == "/basicInfo/personnel") {
//         getList()
//     }
//     next();
// });
</script>

<style lang="scss" scoped>
:deep(.el-table) .success-row {
  background: #dae5f4 !important;
}
</style>
